const mongo = require('../db/mongo')
const COLLECTION = 'user'

/**
 * 登录
 * @param {string} username 
 */
const login = async (username) => {
  let dbo = await mongo()
  const data = { username }
  return await dbo.collection(COLLECTION).find(data).toArray()
}

/**
 * 注册
 * @param {string} username 
 * @param {string} password 
 */
const register = async (username, password) => {
  let dbo = await mongo()
  const data = { username, password }
  const hasUser = await dbo.collection(COLLECTION).find({username: data.username}).toArray()
  if (hasUser.length) return { hasUser: true }
  Object.assign(data, { nickname: '游客', role: 'subscriber' })
  return await dbo.collection(COLLECTION).insertOne(data)
}

/**
 * 获取用户信息
 * @param {string} username 
 */
const getInfo = async (username) => {
  let dbo = await mongo()
  return await dbo.collection(COLLECTION).find({username}).toArray()
}

/**
 * 确认账号有效
 * @param {string} username 
 * @param {string} password 
 */
const confirm = async (username, password) => {
  const data = { username, password }
  let dbo = await mongo()
  return await dbo.collection(COLLECTION).find(data).toArray()
}

/**
 * 修改用户信息
 * @param {string} username 
 * @param {string} password 
 * @param {string} nickname 
 */
const change = async (username, password, nickname) => {
  let dbo = await mongo()
  return await dbo.collection(COLLECTION).updateOne({ username }, {
    $set: { password, nickname }
  })
}

module.exports = {
  login,
  register,
  getInfo,
  confirm,
  change
}
